﻿using Hos.ScheduleMaster.Base;
using Microsoft.Extensions.Hosting;
using NFinal.Common.Plugin;
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace NFinal.Common.PluginTest
{
    class Program
    {
        
        /// <summary>
        /// 运行前请先编译PluginSample项目
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //Test();
            //PluginManager.UnInstall("新闻");
            //Test(out WeakReference weakReference);
            ////简单插件
            //for (int i = 0; weakReference.IsAlive && (i < 10); i++)
            //{
            //    GC.Collect();
            //    GC.WaitForPendingFinalizers();
            //}
            WeakReference weakReference3 = null;
            WWW(out weakReference3);
            for (int i = 0; weakReference3.IsAlive && (i < 10); i++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            Console.ReadKey();

            WeakReference weakReference2 = null;
            PluginWrapper pluginWrapper2 =
                new PluginWrapper(new PluginInfo()
                {
                    AssemblyName = "PluginSample",
                    ClassName = "PluginSample.SimpleService",
                    Name = "PluginSample",
                    PluginFolder = Path.Combine(AppContext.BaseDirectory, "../../../../PluginSample/bin/Debug/netcoreapp3.1")
                }
#if UNLOAD
                , out weakReference2
#endif
                );

            pluginWrapper2.New();
            Console.WriteLine("简单插件已启动");
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            //pluginWrapper2.ExecuteAsync("RunAsync","Li Lei");//可以卸载
            //pluginWrapper2.ExecuteAsync("RunTask", "Li Lei");//可以卸载
            pluginWrapper2.ExecuteAsync("RunWaitTask", "Li Lei");//可以卸载
            //pluginWrapper2.ExecuteAsync("RunWait","Li Lei");//不能卸载
            //pluginWrapper2.ExecuteAsync("RunWaitNewTask", "Li Lei");//不能卸载
            //pluginWrapper2.ExecuteAsync("RunWaitTaskForCancel","Li Lei", cancellationTokenSource.Token);//可以卸载
            Console.WriteLine("插件开始卸载");
            Console.ReadKey();
            cancellationTokenSource.Cancel();
            pluginWrapper2.Execute("Cancel");
            Console.ReadKey();
            pluginWrapper2.UnInstall();
#if UNLOAD
            for (int i = 0; weakReference2.IsAlive && (i < 10); i++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
#endif  
            System.Diagnostics.Debugger.Break();
            Console.Read();
        }

        public static void WWW(out WeakReference weakReference)
        {
            WeakReference weakReference1 = null;
            //pluginWrapper.Execute("Run","Try");
            //实现官方HostedService接口的插件
            CancellationTokenSource cancellationTokenSource1 = new CancellationTokenSource();
            BackgroundServiceA backgroundServiceA = new BackgroundServiceA();
            backgroundServiceA.StartAsync(cancellationTokenSource1.Token).Wait();
            PluginWrapper pluginAsyncWrapper =
                new PluginWrapper(new PluginInfo()
                {
                    AssemblyName = "PluginSample",
                    ClassName = "PluginSample.HostService",
                    Name = "HostService",
                    PluginFolder =Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../PluginSample/bin/Debug/netcoreapp3.1"))
                }
#if UNLOAD
                , out weakReference1
#endif
                );
            weakReference = weakReference1;
            //pluginAsyncWrapper.New();
            var service = pluginAsyncWrapper.New();
            Console.WriteLine("异步插件已启动");
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            pluginAsyncWrapper.ExecuteAsync("StartAsync", cancellationTokenSource.Token);
            //service.StartAsync(cancellationTokenSource.Token);
            Console.WriteLine("请按任意键发出停止信号");
            Console.ReadKey();
            //service.StopAsync(cancellationTokenSource.Token);
            cancellationTokenSource.Cancel();
            cancellationTokenSource.Dispose();
            //pluginAsyncWrapper.Execute("Stop");
            Console.WriteLine("插件开始卸载");
            pluginAsyncWrapper.UnInstall();
            Console.ReadKey();
        }
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void Test(out WeakReference weakReference)
        {
            WeakReference weakReference1 = null;
            PluginWrapper pluginWrapper =
               new PluginWrapper(new PluginInfo()
               {
                   AssemblyName = "PluginSample",
                   ClassName = "PluginSample.SimpleService",
                   Name = "PluginSample",
                   PluginFolder = Path.Combine(AppContext.BaseDirectory, "../../../../PluginSample/bin/Debug/netcoreapp3.1")
               }
#if UNLOAD
               , out weakReference1
#endif
               );
            weakReference = weakReference1;
            pluginWrapper.New();
            Console.WriteLine("简单插件已启动");
            pluginWrapper.Execute("Run", "Li Lei");
            Console.WriteLine("插件开始卸载");
            pluginWrapper.UnInstall();
            System.Diagnostics.Debugger.Break();
            Console.Read();
        }
        //[MethodImpl(MethodImplOptions.NoInlining)]
        //public static void ExecuteAndUnload()
        //{
        //    var alc = new PluginManager();
        //    Assembly a = alc.LoadFromAssemblyPath(assemblyPath);

        //    alcWeakRef = new WeakReference(alc, trackResurrection: true);

        //    var args = new object[1] { new string[] { "Hello" } };
        //    int result = (int)a.EntryPoint.Invoke(null, args);

        //    alc.Unload();

        //    return result;
        //}
        public static void TestA(out WeakReference weakReference)
        {
            TestB(out weakReference);
        }
        public static void TestB(out WeakReference weakReference)
        {
            Test(out weakReference);
        }
        public class BackgroundServiceA : BackgroundService
        {
            protected override Task ExecuteAsync(CancellationToken stoppingToken)
            {
                Console.WriteLine("服务器版本开始执行");
                return Task.CompletedTask;
            }
        }
        //public static void Test1(out WeakReference weakReference)
        //{
        //    //实现官方HostedService接口的插件
        //    PluginWrapper<object> pluginAsyncWrapper =
        //        new PluginWrapper<object>(new PluginInfo()
        //        {
        //            AssemblyName = "SSESpider",
        //            ClassName = "SSESpider.SSEService",
        //            Name = "新闻",
        //            CommonAssemblyFolder = @"D:\mywork\private\source\StockProject\ScheduleMasterCore\src\ScheduleMasterCore\Hos.ScheduleMaster.QuartzHost\wwwroot\plugins\common",
        //            PluginFolder = @"D:\mywork\private\source\StockProject\ScheduleMasterCore\src\ScheduleMasterCore\Hos.ScheduleMaster.QuartzHost\wwwroot\plugins\73fa7e94-32b9-4fab-9dd4-6d9278bf6241"
        //        },out weakReference);
        //    pluginAsyncWrapper.New();
        //    var logger = NFinal.Common.TaskLogger.TaskLoggerFactory.GetTaskLogger(null);
        //    pluginAsyncWrapper.ExecuteAsync("GetModels", "Disclosure.Credibility.BondsDisposition", logger).Wait();
        //    pluginAsyncWrapper.UnInstall();
        //    //for (int i = 0; weakReference.IsAlive && (i < 10); i++)
        //    //{
        //    //    GC.Collect();
        //    //    GC.WaitForPendingFinalizers();
        //    //}
        //    //System.Diagnostics.Debugger.Break();
        //}
    }
}
